<?php
$username = trim($_POST['username']); //通过全局数组$_POST读取前端表单name为username的表单值
$usernameReg = '/^[a-zA-Z0-9]{3,10}$/' ;
if (!preg_match($usernameReg,$username)){
    echo "<script>alert('用户名只能是大小写字母，主子，长度为3-10');historg.back();</script>";
    exit;
}
$pw = trim($_POST['pw']);
$pwReg = "/^[a-zA-Z0-9_\-*]{6，10}$/; ";
if (!preg_match($pwReg,$pw)){
    echo "<script>alert('密码要求只能是大小写字母，数字，_，——，*，长度为6-10');historg.back();</script>";
    exit;
}
$cpw = trim($_POST['cpw']);
if ($pw !== $cpw){
    echo "<script>alert('密码和重复密码必须相同');historg.back();</script>";
    exit;
}
$email = trim($_POST['email']);
$sex = $_POST['sex'];
if($_POST['fav']){
    $fav = implode(",",$_POST['fav']);
}else{
    $fav = "";
}

$pw = md5($pw);
include 'conn.php';
//第三步，设置SQL语句
//判断用户名是否被占用
$sql = "select * from userinto where username = '$username'";
$result = mysqli_query($conn,$sql);//
if(mysqli_num_rows($result)){
    echo "<script>alert('此用户名已被占用');historg.back();</script>";
    exit;
}
$sql = "insert into userinfo (username,pw,email,sex,fav) values ('$username','$pw','$email','$sex','$fav')";
//第四步，执行SQL查询语句
$result = mysqli_query($conn,$sql);
//数据库调试第一招
echo $sql . "<br>";
//数据库调试第二招
echo mysqli_error($conn);
echo "<br>";
if($result){
    echo "<script>alert('数据插入成功');historg.back();</script>";
}
else{
    echo "<script>alert('数据插入失败');historg.back();</script>";
}
